package com.snj.visangedu.lib;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.ContactsContract.Directory;
import android.util.Log;

import com.snj.visangedu.news.News;
import com.snj.visangedu.news.NewsItem;
import com.snj.visangedu.news.NewsLoadInfo;

public class NewsLib {
	
	public static boolean IsLoadingNews = false;
	
	public static NewsLoadInfo newsloader[] = new NewsLoadInfo[3];
	
	public static void InitNews()
	{
		
		new AsyncTask<Integer, String, String>() {

			String tag = "InitNews";
			
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				
				IsLoadingNews = true;
				
				for(int i=0; i<3; i++)
				{
					if(newsloader[i] == null)
					{
						newsloader[i] = new NewsLoadInfo();
					}
				}
			}
			
			@Override
			protected String doInBackground(Integer... params) {
				// TODO Auto-generated method stub
				
				//Log.d(tag, "LoadNews Start");
				
				String currentpath = Global.ex_storage + "/visangedu/";
				String filename = "";
				
				for(int i=0; i<3; i++)
				{
					currentpath = Global.ex_storage + "/visangedu/news" + (i + 1) + "/"; 
					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair("type", "A"));
					postParameters.add(new BasicNameValuePair("begin", "0"));
					postParameters.add(new BasicNameValuePair("count", String.format("%d", params[0])));
					postParameters.add(new BasicNameValuePair("newsid", String.format("%d", i+1)));
					
	            	String result = "";
	            	JSONObject resultobject = null;
	            	
	            	try {
						result = CustomHttpClient.executeHttpPost(Global.newsurl, postParameters);
						//Log.d(tag, result);
						
						//Log.d(tag, "Path : " + Global.ex_storage);
						
						resultobject = new JSONObject(result);
						
						JSONArray newsarr = resultobject.getJSONArray("data");
						JSONObject newsobject = null;
						for(int j=0; j<newsarr.length(); j++)
						{
							newsobject = newsarr.getJSONObject(j);
							
							//Log.d(tag, newsobject.getString("no") + " : " + newsobject.getString("imgsrc"));
							
							filename = newsobject.getString("imgsrc").replace(".jpg", ".vnews").replace(".png", ".vnews") + newsobject.getString("updatever");
							
							newsloader[i].Add(new News(newsobject.getString("no"), currentpath + filename, newsobject.getString("imgsrc")));
							
							File file = new File(currentpath + filename);
							
							Bitmap newsimg = null;
							
							
							if(!file.exists())
							{
								newsimg = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "newsimages" + (i + 1) + "/" + newsobject.getString("imgsrc"));
								Global.saveBitmaptoJpeg(newsimg, "visangedu/news" + (i + 1), filename);
								//Log.d(tag, "Save : " + currentpath + filename);
								//Log.d(tag, "Download : " + filename);
							}
							 
							//Log.d(tag, "No : " + newsobject.getString("no"));
							//newsloader[i].Add(new News(newsobject.getString("no"), newsimg));
							
							//newsimg.recycle();
							
						} 
						
						
	            	}
	            	catch(Exception e)
	            	{
	            		e.printStackTrace();
	            	}
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				IsLoadingNews = false;
			}
			
			
		}.execute(65);
		
		
	}
	
	public static void LoadNews(int newsid, int count)
	{
		ArrayList<News> arr_news = NewsLib.newsloader[newsid].GetNewsArray();
		
		News lastnews = arr_news.get(arr_news.size() - 1);
		
		new AsyncTask<String, String, String>() {

			String tag = "InitNews";
			
			
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				
				String currentpath = Global.ex_storage + "/visangedu/";
				String filename = "";
				
				for(int i=0; i<3; i++)
				{
					currentpath = Global.ex_storage + "/visangedu/news" + (i + 1) + "/"; 
					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair("type", "A"));
					postParameters.add(new BasicNameValuePair("begin", params[1]));
					postParameters.add(new BasicNameValuePair("count", params[2]));
					postParameters.add(new BasicNameValuePair("newsid",params[0]));
					
	            	String result = "";
	            	JSONObject resultobject = null;
	            	
	            	try {
	            		Log.d("LoadNews", "request : " + postParameters.toString());
						result = CustomHttpClient.executeHttpPost(Global.newsurl, postParameters);
						Log.d("LoadNews", "response : " + result);
						
						Log.d(tag, "Path : " + Global.ex_storage);
						
						resultobject = new JSONObject(result);
						
						JSONArray newsarr = resultobject.getJSONArray("data");
						JSONObject newsobject = null;
						
						
						/*
						for(int j=0; j<newsarr.length(); j++)
						{
							newsobject = newsarr.getJSONObject(j);
							
							//Log.d(tag, newsobject.getString("no") + " : " + newsobject.getString("imgsrc"));
							
							filename = newsobject.getString("imgsrc").replace(".jpg", ".vnews").replace(".png", ".vnews");
							
							File file = new File(currentpath + filename);
							
							Bitmap newsimg = null;
							
							if(file.exists())
							{
								Log.d(tag, "1st : Load from local");
								newsimg = BitmapFactory.decodeFile(currentpath + filename);
							}
							
							if(newsimg == null)
							{
								newsimg = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "newsimages" + (i + 1) + "/" + newsobject.getString("imgsrc"));
								Global.saveBitmaptoJpeg(newsimg, "visangedu/news" + (i + 1), filename);
								Log.d(tag, "Save : " + currentpath + filename);
								Log.d(tag, "Download : " + filename);
							}
							 
							Log.d(tag, "No : " + newsobject.getString("no"));
							newsloader[i].Add(new News(newsobject.getString("no"), newsimg));
							
							
						} */
						
						
	            	}
	            	catch(Exception e)
	            	{
	            		e.printStackTrace();
	            	}
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}
			
			
		}.execute(String.format("%d", newsid + 1), String.format("%d", arr_news.size()), String.format("%d", count));
	}
	
	public static void GetNews(int newsid, int begin, int end)
	{
		
	}
	
	public static long folderMemoryCheck(String a_path){
		long totalMemory = 0;
		File file = new File(a_path);
		File[] childFileList = file.listFiles();

		if(childFileList == null){
		return 0;
		}

		for(File childFile : childFileList){
		if(childFile.isDirectory()){
		totalMemory += folderMemoryCheck(childFile.getAbsolutePath());

		}
		else{
		totalMemory += childFile.length();
		}
		}
		return totalMemory;
		}
}
